#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include "DriverLcd.h"
#include "DriverFile.h"
#include "DriverImage.h"


extern _lcd_dev lcddev;


int8_t cImageBmpShow(char *pucFileName)
{
    uint32_t uiAddress = 54;
    int32_t iLength565, iLength888, x, y, i;
    uint16_t usRGB565;
    uint8_t bufRGB888[60], bufRGB565[40];

    if(pucFileName == NULL)
        return 1;

    if(iFileSizeGet(pucFileName) > 0)
    {
        for(y = lcddev.height - 1; y >= 0; --y)
        {
            for(x = 0; x < lcddev.width; x += sizeof(bufRGB565) / 2)
            {
                vLcdSetWindows(x, y, lcddev.width - 1, y);

                iLength565 = (lcddev.width - x) * 2 > sizeof(bufRGB565) ? sizeof(bufRGB565) : (lcddev.width - x) * 2;
                iLength888 = (iLength565 * 24) / 16;

                cFileRead(pucFileName, uiAddress, bufRGB888, iLength888);
                uiAddress += iLength888;

                /* RGB888 TO RGB565 */
                for(i = 0; i < iLength888; i += 3)
                {
                    usRGB565 = ((uint16_t)(bufRGB888[i + 2] & 0xF8) << 8) | ((uint16_t)(bufRGB888[i + 1] & 0xFC) << 3) | (bufRGB888[i + 0] >> 3);

                    bufRGB565[(i * 2) / 3 + 1] = usRGB565;
                    bufRGB565[(i * 2) / 3 + 0] = usRGB565 >> 8;
                }

                vLcdWriteDatas(bufRGB565, iLength565);
            }
        }
    }

    return 0;
}
